<template>
  
  <van-nav-bar
  title="登录"
/>
  <div style="text-align: center;">
    <van-image round  width="100px"  height="100px"    src="https://fastly.jsdelivr.net/npm/@vant/assets/cat.jpeg"/>
    <van-field v-model="phone" label="手机号" placeholder="请输入手机号" />
    <van-field
        v-model="sms"
        center
        clearable
        label="短信验证码"
        placeholder="请输入短信验证码"
      >
        <template #button>
          <van-button size="small" type="primary" @click="sendmes">发送验证码</van-button>
        </template>
      </van-field>
      <div class="third-party-login">
        <van-button type="default" icon="weibo" class="custom-icon" @click="" color="#e64340"/>
        <van-button type="default" icon="wechat" class="custom-icon" @click="" color="green" />
        <van-button type="default" icon="alipay" class="custom-icon" @click="" color="#1989fa"/>
        <van-button type="default" color="#3f9fff" icon="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fc-ssl.duitang.com%2Fuploads%2Fitem%2F202004%2F22%2F20200422200856_zgdim.jpg&refer=http%3A%2F%2Fc-ssl.duitang.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1743246361&t=570fc241176c3e80118187e2b266388e" class="custom-icon" 
        @click="loginWithDingtalk" />
      </div>
    <van-button type="primary" @click="login" style=" width: 100%; margin-top: 20px;">登录</van-button>

  </div>
 </template>

<script lang="ts" setup >
import { ref,onMounted, h } from 'vue';
import { useRouter } from 'vue-router';
import http from '../http/index.js';
import { showSuccessToast, showFailToast, showLoadingToast } from 'vant';

let phone=ref('');
let sms=ref('');
let router=useRouter();
const sendmes=()=>{
  http.post('/user/send/',{phone:phone.value}).then(res=>{
    if(res.data.code==200){
      showSuccessToast('发送成功,验证码为'+res.data.sms);

    }else{
      showFailToast('发送失败');
    }
  })
}
const login=async ()=>{
  const toast = showLoadingToast({
    duration: 0,
    forbidClick: true,
    message: '登录中...'
  });
  
  try {
    const res = await http.post('/user/login/',{
      phone:phone.value,
      code:sms.value
    });
    
    if(res.data.code===200){
      storeUserAuthInfo(res);
      showSuccessToast('登录成功');
      router.push('/my');
    } else {
      showFailToast(res.data.msg || '登录失败');
    }
  } catch (error) {
    showFailToast(error.response?.data?.message || '网络请求异常');
  } finally {
    toast.close();
  }
}

// 统一认证信息存储
const storeUserAuthInfo = (data:any) => {
  localStorage.setItem('token', data.data.token);
  localStorage.setItem('retoken', data.data.retoken);
  localStorage.setItem('userid', data.data.userid);
  localStorage.setItem('userInfo', JSON.stringify(data.data.userInfo));
}

// 三方登录（示例钉钉登录）
const loginWithDingtalk=async ()=>{
  try {
    const res = await http.post('/user/dd/login/',{
      code: urlParams.get('code'),
      authCode: urlParams.get('authCode'),
      types:'dingding'
    });
    
    if(res.data.code===200){
      window.open(res.data.url)
    }
  } catch (error) {
    showFailToast('三方登录失败');
  }
}
const urlParams = new URLSearchParams(window.location.search);
const code = urlParams.get('code');        // 获取 ed7c22c5365c3defa0c9deb2d9c6de5a
const authCode = urlParams.get('authCode');
const loback=async ()=>{
  const toast = showLoadingToast({
    duration: 0,
    forbidClick: true,
    message: '登录中...'
  });

  try {
    const res = await http.get('/user/dd/login/callback/',{
      params: {
        code: code,
        authCode: authCode,
        types: 'dingding'
      }
    });

    if(res.data.code===200){
      storeUserAuthInfo(res.data);
      showSuccessToast('登录成功');
      await router.push('/home');
    } else {
      showFailToast(res.data.msg || '登录失败');
    }
  } catch (error) {
    showFailToast(error.response?.data?.message || '网络请求异常');
  } finally {
    // 修复：使用 close 方法替代不存在的 clear 方法
    toast.close();
  }
}
onMounted(()=>{
  if (code && authCode) {
    loback();
  }
  
  
})

</script>